package com.cr.business.service.impl;

import com.cr.business.domain.*;
import com.cr.business.domain.dto.QualifiedCertReqDto;
import com.cr.business.domain.dto.app.QualifiedCertListParam;
import com.cr.business.domain.dto.app.QualifiedCertPrintParam;
import com.cr.business.domain.vo.AppCertListData;
import com.cr.business.domain.vo.AppProducerInfoData;
import com.cr.business.domain.vo.QualifiedCertDataVo;
import com.cr.business.domain.vo.QualifiedCertDetailInfoVo;
import com.cr.business.mapper.*;
import com.cr.business.service.ITbQualifiedCertInfoService;
import com.cr.common.exception.ServiceException;
import com.cr.common.utils.DateUtils;
import com.cr.common.utils.SecurityUtils;
import com.cr.common.utils.StringUtils;
import com.cr.common.utils.uuid.IdUtils;
import com.cr.common.utils.uuid.RandomUtil;
import com.cr.common.utils.uuid.SnowflakeIdGenerator;
import com.cr.system.service.ISysDictDataService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 合格证信息Service业务层处理
 * 
 * @author tang
 * @date 2025-08-19
 */
@Service
public class TbQualifiedCertInfoServiceImpl implements ITbQualifiedCertInfoService 
{
    @Resource
    private TbQualifiedCertInfoMapper tbQualifiedCertInfoMapper;

    @Resource
    private TbProductInfoMapper tbProductInfoMapper;

    @Resource
    private TbProducerInfoMapper tbProducerInfoMapper;

    @Resource
    private TbUserBaseInfoMapper tbUserBaseInfoMapper;

    @Resource
    private TbUserEntityCheckCountMapper tbUserEntityCheckCountMapper;

    @Resource
    private ISysDictDataService dictDataService;

    @Resource
    private TbQualifiedCertPrintCountMapper tbQualifiedCertPrintCountMapper;

    /**
     * 查询合格证信息
     * 
     * @param certId 合格证信息主键
     * @return 合格证信息
     */
    @Override
    public QualifiedCertDetailInfoVo selectTbQualifiedCertInfoByCertId(String certId)
    {
        // 合格证详情
        QualifiedCertDetailInfoVo certDetailInfoVo = tbQualifiedCertInfoMapper.selectTbQualifiedCertInfoByCertId(certId);
        // 生产人签名
        AppProducerInfoData appProducerInfoData = tbProducerInfoMapper.selectAppProducerInfoByProducerId(certDetailInfoVo.getProducerId());
        if (appProducerInfoData != null) {
            certDetailInfoVo.setProducerSign(appProducerInfoData.getSignImg());
        }
        return certDetailInfoVo;
    }

    @Override
    public QualifiedCertDetailInfoVo appGetQualifiedCertInfo(String certId)
    {
        QualifiedCertDetailInfoVo qualifiedCertDetailInfoVo = tbQualifiedCertInfoMapper.selectTbQualifiedCertInfoByCertId(certId);
        if(qualifiedCertDetailInfoVo == null) {
            return null;
        }
        // 计量单位
        qualifiedCertDetailInfoVo.setUnit(dictDataService.selectDictLabel("unit_of_measurement", qualifiedCertDetailInfoVo.getUnit()));

        // 生产人签名
        AppProducerInfoData appProducerInfoData = tbProducerInfoMapper.selectAppProducerInfoByProducerId(qualifiedCertDetailInfoVo.getProducerId());
        if (appProducerInfoData != null) {
            qualifiedCertDetailInfoVo.setProducerSign(appProducerInfoData.getSignImg());
        }

        return qualifiedCertDetailInfoVo;
    }

    /**
     * 查询合格证信息列表
     * 
     * @param dto 查询参数
     * @return 合格证信息
     */
    @Override
    public List<QualifiedCertDataVo> selectTbQualifiedCertInfoList(QualifiedCertReqDto dto)
    {
        return tbQualifiedCertInfoMapper.selectTbQualifiedCertInfoList(dto);
    }

    /**
     * 批量删除合格证信息
     * 
     * @param certIds 需要删除的合格证信息主键
     */
    @Override
    public int deleteTbQualifiedCertInfoByCertIds(String[] certIds)
    {
        return tbQualifiedCertInfoMapper.deleteTbQualifiedCertInfoByCertIds(certIds);
    }

    @Override
    public Map<String, Object> appCertList(QualifiedCertListParam param) {
        // 当前用户
        String appUserId = SecurityUtils.getAppUserId();
        param.setUserId(appUserId);

        // 分页查询
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<AppCertListData> dbList = tbQualifiedCertInfoMapper.selectAppCertListData(param);
        PageInfo<AppCertListData> pageInfo = new PageInfo<>(dbList);
        PageHelper.clearPage();

        // 封装返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("data", pageInfo.getList());
        map.put("total", pageInfo.getTotal());
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addCert(TbQualifiedCertInfo info) {

        // 判断用户实名状态
        String appUserId = SecurityUtils.getAppUserId();
        TbUserBaseInfo tbUserBaseInfo = tbUserBaseInfoMapper.selectTbUserBaseInfoByUserId(appUserId);
        if (tbUserBaseInfo == null ) {
            throw new RuntimeException("用户信息不存在！");
        }
        if(! "1".equals(tbUserBaseInfo.getAuthStatus())) {
            throw new RuntimeException("用户未完成实名认证！");
        }
        String entityId = tbUserBaseInfo.getEntityId();

        // 判断承诺依据
        String promiseStr = validPromise(info.getPromise());
        info.setPromise(promiseStr);

        // 1、产品信息处理
        String paramProductId = info.getProductId();
        // 根据ID查询
        TbProductInfo productInfo = tbProductInfoMapper.selectTbProductInfoByProId(paramProductId);
        if(productInfo == null) {
            // 再根据名称查询
            productInfo = tbProductInfoMapper.selectByName(StringUtils.trim(paramProductId));
            if(productInfo == null) {
                // 添加产品
                productInfo = insertProduct(paramProductId);
            }
        }
        info.setProductId(productInfo.getProId());
        info.setProductName(productInfo.getProName());

        // 2、生产人信息处理
        TbProducerInfo tbProducerInfo = tbProducerInfoMapper.selectTbProducerInfoByProducerId(info.getProducerId());
        if (tbProducerInfo == null) {
            throw new RuntimeException("生产人信息不存在！");
        }
        info.setProducerId(tbProducerInfo.getProducerId());
        info.setProducerName(tbProducerInfo.getProducerName());
        info.setProducerPhone(tbProducerInfo.getProducerPhone());

        // 3、添加合格证数据
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(RandomUtil.getRandomNumber(10, 1000));
        info.setCertId(String.valueOf(idGenerator.nextId()));
        info.setCertNo(DateUtils.dateTimeNow("yyyyMMddHHmmssSSS") + RandomUtil.getRandomNumber(100, 900));
        info.setUserId(appUserId);
        info.setEntityId(entityId);
        int i = tbQualifiedCertInfoMapper.insertTbQualifiedCertInfo(info);

        // 4、增加产品开具合格证次数
        tbProductInfoMapper.addProductQuantity(productInfo.getProId());

        // 5、增加主体检测次数
        saveCheckCount(promiseStr, entityId);

        return i;
    }

    /**
     * 验证承诺依据的值是否合法
     * @param promise
     */
    private String validPromise (String promise) {
        if(StringUtils.isBlank(promise)) {
            throw new RuntimeException("承诺依据不能为空！");
        }
        String[] promiseArr = promise.split(",");
        StringBuilder finalPromise = new StringBuilder();
        for (String s : promiseArr) {
            if(StringUtils.isNotBlank(s) && ("1".equals(s) || "2".equals(s) || "3".equals(s) )) {
                if(StringUtils.isNotBlank(finalPromise.toString())) {
                    finalPromise.append(",");
                }
                // 如果不为空且是合法的值，则保存
                finalPromise.append(s);
            }
        }
        if(StringUtils.isBlank(finalPromise.toString())) {
            throw new RuntimeException("承诺依据传值不合法！");
        }
        return finalPromise.toString();
    }

    /**
     * 新增产品
     * @param name
     */
    private TbProductInfo insertProduct(String name) {
        TbProductInfo productInfo = new TbProductInfo();
        productInfo.setProId(IdUtils.simpleUUID());
        productInfo.setProName(name);
        productInfo.setCreatorType("1");

        String nickName = SecurityUtils.getAppLoginUser().getUser().getNickName();
        Date nowDate = DateUtils.getNowDate();
        productInfo.setCreateBy(nickName);
        productInfo.setCreateTime(nowDate);
        productInfo.setUpdateBy(nickName);
        productInfo.setUpdateTime(nowDate);
        tbProductInfoMapper.insertTbProductInfo(productInfo);
        return productInfo;
    }

    /**
     * 保存主体检测次数
     * @param promiseStr 承诺依据
     * @param entityId 主体ID
     */
    private void saveCheckCount(String promiseStr, String entityId){
        String[] split = promiseStr.split(",");
        int wt = 0;
        int zx = 0;
        for (String s : split) {
            // 承诺依据，多个值以英文逗号隔开（1-质量安全控制符合要求，2-委托检测合格，3-自行检测合格）
            if("2".equals(s)) {
                wt += 1;
            }
            if("3".equals(s)) {
                zx += 1;
            }
        }
        TbUserEntityCheckCount entityCheckCount = tbUserEntityCheckCountMapper.selectTbUserEntityCheckCountByEntityId(entityId);
        if(entityCheckCount != null) {
            zx += entityCheckCount.getSelfCheck();
            wt += entityCheckCount.getEntrustCheck();
            entityCheckCount.setSelfCheck(zx);
            entityCheckCount.setEntrustCheck(wt);
            tbUserEntityCheckCountMapper.updateTbUserEntityCheckCount(entityCheckCount);
        } else {
            entityCheckCount = new TbUserEntityCheckCount();
            entityCheckCount.setEntityId(entityId);
            entityCheckCount.setSelfCheck(zx);
            entityCheckCount.setEntrustCheck(wt);
            tbUserEntityCheckCountMapper.insertTbUserEntityCheckCount(entityCheckCount);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePrintData(List<QualifiedCertPrintParam> params) {
        if (params == null || params.isEmpty()) {
            throw new RuntimeException("参数不能为空！");
        }

        Date nowDate = DateUtils.getNowDate();
        for (QualifiedCertPrintParam param : params) {
            String certId = param.getCertId();
            TbQualifiedCertInfo info = tbQualifiedCertInfoMapper.selectBaseInfoByCertId(certId);
            if (info != null) {
                info.setPrintQuantity(info.getPrintQuantity() + param.getNum());
                tbQualifiedCertInfoMapper.updateTbQualifiedCertInfo(info);

                // 添加打印记录
                TbQualifiedCertPrintCount printCount = new TbQualifiedCertPrintCount();
                printCount.setCertId(certId);
                printCount.setUserId(info.getUserId());
                printCount.setEntityId(info.getEntityId());
                printCount.setQuantity(param.getNum());
                printCount.setPrintDate(nowDate);
                tbQualifiedCertPrintCountMapper.insertTbQualifiedCertPrintCount(printCount);
            }
        }
    }

    @Override
    public Map<String, Object> getAppIndexData() {
        // 合格证数据
        QualifiedCertListParam param = new QualifiedCertListParam();
        param.setPage(1);
        param.setPageSize(5);
        Map<String, Object> certCounts = appCertList(param);

        // 合格证打印张数
        String appUserId = SecurityUtils.getAppUserId();
        int sumPrintQuantity = tbQualifiedCertInfoMapper.getSumPrintQuantity(appUserId);
        certCounts.put("allPrintQuantity", sumPrintQuantity);
        return certCounts;
    }

    @Override
    public List<AppCertListData> getPrintInfo(String ids) {
        if(StringUtils.isBlank(ids)) {
            throw new ServiceException("合格证ID不能为空！");
        }
        String[] idArr = ids.split(",");
        return tbQualifiedCertInfoMapper.selectPrintCertList(idArr);
    }
}
